package com.pzh.vue.controller;


import com.pzh.vue.mapper.DictMapper;
import com.pzh.vue.pojo.Dict;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.vue.common.Constants;
import com.pzh.vue.common.Result;
import com.pzh.vue.exception.ServiceException;
import com.pzh.vue.pojo.Menu;
import com.pzh.vue.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xzh
 * @since 2022-03-27
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

     @Autowired
      private IMenuService menuService;
     @Autowired
     private DictMapper dictMapper;
     @GetMapping
     public Result findAll(){
         List<Menu> parentNode = menuService.findAll();
         return Result.success(parentNode);
        }
     @PostMapping(value = "/update")
     public Result saveMenu(@RequestBody Menu menu ){
        System.out.println(menu);
        try {
        menuService.saveOrUpdate(menu);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success();
        }
     @GetMapping("/page")
     public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(defaultValue = "") String name){
        IPage<Menu> page=new Page<Menu>(pageNum,pageSize);
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if (!(name==null)){
        queryWrapper.like("name",name);
        }
        try {
        menuService.page(page, queryWrapper);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success(page);
        }
       @PostMapping("/save")
       public boolean save(@RequestBody Menu menu) {
        QueryWrapper<Menu> menuName = new QueryWrapper<Menu>().eq("name", menu.getName());
       Menu one = menuService.getOne(menuName,false);
        if (one==null){
       menu.setId(null);
        }
        else {menu.setId(one.getId());}
        boolean save = menuService.saveOrUpdate(menu);
        return save;
        }
      @DeleteMapping("/{id}")
      public Result delete(@PathVariable Integer id){
        try {
      menuService.removeById(id);
        }catch (Exception e){
        throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success();
        }
@GetMapping("/export")
public void exportExel(HttpServletResponse response) throws IOException {
        //查询所有用户
        List<Menu> list=menuService.list();
        //在内存操作，写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
        //默认配置
        writer.write(list,true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();
        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        }

/**
 * 导入excel
 * @param file
 */
@PostMapping("/import")
public void importExcel(MultipartFile file) throws IOException {
        //1.第一种 头必须和实体一样
        //文件处理成io流
        InputStream in=file.getInputStream();
        //io流给ExcelReader
        ExcelReader excelReader=ExcelUtil.getReader(in);
        //读取数据且转化为list
        List<Menu> list=excelReader.readAll(Menu.class);
        //第二种导入方式
        //忽略第一行头
       /* List<List<Object>> list=excelReader.read(1);
        List<SysUser> listUser= CollUtil.newArrayList();
        for (List<Object> row: list) {
            SysUser user=new SysUser();
            user.setUsername(row.get(0).toString());
            *//*****类似一一对应*****//*
        }*/
        //批量注册进数据库
        menuService.saveBatch(list);
        }
        @GetMapping("/icon")
        public Result findIcon(){
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("type",Constants.DICT_TYPE_INCO);
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        return Result.success(dicts);
        }
}

